<?php
// ----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// ----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// ----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// ----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// ----------------------------------------------------------------------

// 应用公共文件

/**
 * 计算当前分页:用于sql limit;
 * @param int $page
 * @param int $offset
 * @return string
 */
function cnt_page(int $page = 0, int $offset = 10): string
{
    $page  = $page <= 1 || empty($page) ? 0 : ($page - 1) * $offset;
    $limit = "$page , $offset";
    return $limit;
}

/**
 * 创建密码;
 * 自动匹配系统当前最好额度cost;
 * @param string $password
 * @return string
 */
function create_password(string $password): string
{
    $timeTarget = 0.05; // 50 毫秒（milliseconds）
    $cost       = 8;
    do {
        $cost++;
        $start = microtime(true);
        password_hash("test", PASSWORD_BCRYPT, ["cost" => $cost]);
        $end = microtime(true);
    } while (($end - $start) < $timeTarget);
    return password_hash($password, PASSWORD_DEFAULT, ['cost' => $cost]);
}

/**
 * 数据加密;
 * 若不设置 $hour 则默认保存 有效时间为 2小时 , 即 120分钟;
 * @param array $data
 * @param string $key
 * @param int $hour
 * @return string
 */
function encrypt(array $data, string $key, int $hour = 0): string
{
    if ($hour) {
        $time                   = time();
        $effective_time         = $hour * 60 * 60;
        $data['save_status']    = true;
        $data['start_time']     = $time;
        $data['end_time']       = $time + $effective_time;
        $data['effective_time'] = $effective_time;
    }
    return \crypt\Crypt::encrypt(json_encode($data), $key);
}

/**
 * 数据解密;
 * @param string $token
 * @param string $key
 * @return array
 */
function decrypt(string $token, string $key): array
{
    $decrypt = json_decode(\crypt\Crypt::decrypt($token, $key), true);
    if (isset($decrypt['save_status'])) {
        $decrypt['save_status'] = time() - $decrypt['start_time'] > $decrypt['effective_time'] ? false : true;
    }
    return $decrypt;
}

/**
 * 上传文件；
 * @param $file
 * @param string $dir
 * @return array
 */
function upload($file, string $dir)
{
    $path = $dir . '/';
    $info = $file->move('../public/uploads/' . $path);
    $ret  = $info ? $info->getSaveName() : false;
    if ($ret) {
        return [
            'file_name' => $path . $ret,
            'status'    => 200,
            'msg'       => '上传成功',
        ];
    } else {
        return [
            'file_name' => $ret,
            'status'    => 500,
            'msg'       => 'upload file fail',
        ];
    }
}

/**
 * 删除文件；
 * @param string $path
 * @return bool
 */
function del_file(string $path)
{
    return unlink('../public/uploads/' . $path);
}

/**
 * 解析code
 */
if (!function_exists('get_code')) {
    /**
     * @param $key
     * @param null $code
     * @return array|mixed|null
     */
    function get_code($key, $code = null)
    {
        $config = config("code.{$key}");

        if (!$code && $code != 0) {
            return null;
        }

        // 判断是否为数组
        if (is_array($code)) {
            $data = [];
            foreach ($code as $item) {
                $data[] = isset($config[$item]) ? $config[$item] : null;
            }
            return $data;
        }

        return isset($config[$code]) ? $config[$code] : null;
    }
}

/**
 * 解析code
 */
if (!function_exists('get_code_array')) {
    /**
     * @param $key
     * @return array|mixed|null
     */
    function get_code_array($key)
    {
        $config = config("code.{$key}");
        if (!$config && count($config) <= 0) {
            return [];
        }
        return $config;
    }
}


if (!function_exists('mk_order_sn')) {

    /**
     * 生成订单号
     *
     * @return string
     */
    function mk_order_sn()
    {
        $sn = date('ymdHi') . rand(10, 99);

        return $sn;
    }
}

if (!function_exists('admin_upload')) {
    /**
     * 图片上传
     * @param $file
     * @param $dir
     * @param $width
     * @param $height
     * @return array
     */
    function admin_upload($file, $dir, $width, $height) {
        $path = '../public/uploads/' ;
        $fileName = $dir . '/' . date('Ymd') . '/' . sprintf('%04d', mt_rand(1, 999999999999)) . '.jpg';
        $image = \think\Image::open($file);
        // 判断文件夹
        $dirPath = $path . $dir . '/' . date('Ymd');
        if(!is_dir($dirPath)) {
            // 创建
            mkdir ($dirPath,0777,true);
        }
        if ($height == -1) {
            $scale = $width / $image->width();
            $height = $image->height() * $scale;
        }
        $bool = $image->thumb($width, $height, \think\Image::THUMB_CENTER)->save($path . $fileName);
        if ($bool) {
            return [
                'file_name' => $fileName,
                'status'    => 200,
                'msg'       => '上传成功',
            ];
        } else {
            return [
                'file_name' => $fileName,
                'status'    => 500,
                'msg'       => 'upload file fail',
            ];
        }
    }
}

if (!function_exists('admin_upload_base64')) {
    /**
     * base64 上传
     * @param $base64
     * @param $dir
     * @param $width
     * @param $height
     * @return array|bool
     */
    function admin_upload_base64($base64, $dir, $width, $height) {
        $base64_image = str_replace(' ', '+', $base64);
        //post的数据里面，加号会被替换为空格，需要重新替换回来，如果不是post的数据，则注释掉这一行
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image, $result)){
            if($result[2] == 'jpeg'){
                $image_name = uniqid().'.jpg';
                //纯粹是看jpeg不爽才替换的
            }else{
                $image_name = uniqid().'.'.$result[2];
            }
            $image_file = "../public/uploads/test/{$image_name}";
            //服务器文件存储路径
            if (file_put_contents($image_file, base64_decode(str_replace($result[1], '', $base64_image)))){
                $ret = admin_upload($image_file, $dir, $width, $height);
                if ($ret['status'] == 500) {
                    return false;
                }
                // 删除照片
                del_file('test/' . $image_name);
                return $ret;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }
}


if (!function_exists('get_img_url')) {
    /**
     * 获取图片
     * @param $path
     * @return string|null
     */
    function get_img_url($path) {
        if (!$path) {
            return null;
        }
        return 'https://api.hs.zcollar.cn/' . $path;
    }
}
